package com.yuchen.ishop.web.app.interceptor;

import com.yuchen.ishop.service.buyer.BuyerRestClient;
import com.yuchen.ishop.service.goods.GoodsRestClient;
import com.yuchen.ishop.vo.CookieUserInfo;
import com.yuchen.ishop.web.BaseAction;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Jack Q
 *         商品拦截
 */
public class GoodsInterceptor implements HandlerInterceptor {

    private final static Logger LOG = Logger.getLogger(GoodsInterceptor.class);

    @Autowired
    private GoodsRestClient goodsRestClient;

    @Autowired
    private BuyerRestClient buyerRestClient;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOG.debug(request.getServletPath());
        String url = request.getServletPath();
        if (url.startsWith("/detail.htm")) {
            String id = request.getParameter("id");
            if (StringUtils.isBlank(id)) {
                response.sendRedirect(request.getContextPath() + "/error.htm");
                return false;
            }
            Long goodsId = Long.valueOf(request.getParameter("id"));
            if (!goodsRestClient.isAccessGoods(goodsId)) {
                response.sendRedirect(request.getContextPath() + "/error.htm");
                return false;
            }

            CookieUserInfo userInfo = BaseAction.cookie2UserInfo(request);
            if (userInfo != null && userInfo.isState() && "buyer".equals(userInfo.getRole())) {
                Long buyerId =  userInfo.getId();
                buyerRestClient.goodsTrace(buyerId,goodsId);
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
